package com.yc154.filter;

import com.yc154.util.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class CustomAuthGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 0. 判断是否需要做用户鉴权, 如果是, 则直接放行
        String path = exchange.getRequest().getURI().getPath();
        if (path.startsWith("/auth")||
                path.startsWith("/talk")||
                path.startsWith("/user/")||
                path.startsWith("/cloud-user/")||
                path.startsWith("/cloud-other/")||
//                path.startsWith("/user/autoLogin")||
                path.startsWith("/cloud-mobile")||
                path.startsWith("/index/")) {
            return chain.filter(exchange);
        }
        // 1. 实现你的过滤逻辑，例如获取请求头中的token并进行验证:cite[4]
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            try {
                JwtUtils.parseJWT(token);
                // 2.  token验证通过，放行请求到下一个过滤器或下游服务:cite[4]
                return chain.filter(exchange);
            } catch (Exception e) {
                // continue
            }
        }
        // 3.  token验证失败，拦截请求并返回未授权状态码:cite[4]
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
    @Override
    public int getOrder() {
        // 4. 返回过滤器的执行顺序，值越小优先级越高:cite[3]:cite[5]
        return 0;
    }
}
